<template>
  <ex-dialog width="40%" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm"
      v-loading="loading">
      <el-form-item label="区域名称：" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入区域名称" style="width:90%"></el-input>
      </el-form-item>
      <el-form-item label="管辖区域：" prop="areaList">
        <!-- <el-cascader v-model="ruleForm.areaList" :options="options"
          :props="{ value: 'id',label: 'label',children: 'children', multiple: true,disabled:'isNotAvailable'}"
          clearable style="width:90%" placeholder="请选择管辖区域" @change="handleCityChange">
        </el-cascader> -->
        <el-cascader filterable clearable v-model="ruleForm.areaList" :options="cityList" style="width:90%"
          placeholder="请选择管辖区域"
          :props="{ value: 'id',label: 'label',children: 'children', multiple: true,disabled:'isNotAvailable',checkStrictly: true}"
          @change="handleCityChange"></el-cascader>
      </el-form-item>
      <el-form-item label="购卡冷静期：" prop="coolingOffDay" ref="coolingOffDayRef">
        <el-input :disabled="ruleForm.coolingOffType=='1'?true:false" v-model="ruleForm.coolingOffDay" placeholder="请输入"
          style="width:90%">
          <template slot="append">天内购卡可无理由退卡</template></el-input>
      </el-form-item>
      <el-form-item label="" prop="coolingOffType">
        <el-checkbox v-model="ruleForm.coolingOffType" true-label="1" false-label="2" @change="checkboxChange">无限冷静期</el-checkbox>
      </el-form-item>
      <el-form-item label="排序：" prop="sort">
        <el-input v-model="ruleForm.sort" placeholder="请输入排序序号" style="width:90%"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')" :loading="submitLoading" v-if="id==null">确 定</el-button>
      <el-button type="primary" @click="editForm('ruleForm')" :loading="submitLoading" v-if="id!=null">保 存</el-button>
    </span>
  </ex-dialog>
</template>
<script>
  import {
    getAreaSelect,
    addArea,
    getAreaDetail,
    editArea
  } from "@/api/setting";
  import Loading from "@/components/Loading/index";
  import Editor from '@/components/Editor';

  export default {
    components: {
      Loading,
      Editor,
    },
    props: {
      visible: Boolean,
      id: String,
    },
    data() {
      var valicoolingOffDay = (rule, value, callback) => {
        var reg = /(^[1-9]\d*$)/;
        if (!value && this.ruleForm.coolingOffType=='2') {
          return callback(new Error('请输入'));
        }
        else if (!reg.test(value) && this.ruleForm.coolingOffType=='2') {
          return callback(new Error('请输入大于0的整数'));
        } else {
          callback();
        }
      };
      return {
        title: '新建区域',
        loading: false,
        submitLoading: false,
        formInline: {
          name: "", //区域名称
        },
        title: '添加区域', //
        props: {
          multiple: true
        },
        cityList: [],
        ruleForm: {
          name: "", //区域名称
          areaList: [], //区域
          sort: "", //推荐序号
          coolingOffType: '2', //冷静期类型 1 无冷静期 2 限制天数
          coolingOffDay: '1', //冷静期天数
        },
        rules: {
          name: [{
            required: true,
            message: "请输入区域名称",
            trigger: ['blur', 'change']
          }, ],
          areaList: [{
            required: true,
            message: "请选择区域",
            trigger: "blur"
          }],
          coolingOffDay: [{
            required: true,
            validator: valicoolingOffDay,
            trigger: ['blur', 'change']
          }],
          sort: [{
            required: true,
            message: "请输入排序号",
            trigger: ['blur', 'change']
          }, ],
        },
        editId: '', //编辑id
      };
    },
    computed: {},
    created() {
      console.log(this.id)
      if (this.id != null) {
        this.getSelect()
        this.title = '编辑区域'
        this.getInfo()
      } else {
        this.getSelect(this.id)
      }
    },
    methods: {
      //取消
      handleClose(formName) {
        this.$emit("update:visible", false);
      },
      getSelect(id) { //查询区域下拉框
        var params = {
          id: this.id
        }
        getAreaSelect(params).then((res) => {
          this.cityList = res.result;
          this.cityList.forEach((item) => {
            item.children.forEach((items) => {
              items.children.forEach((itemss) => {
                if (itemss.children.length == 0) {
                  itemss.children = null
                }
              })
            })
          })
        });
      },
      handleCityChange(array) {
        console.log(array)
      },
      checkboxChange(e){ //冷静期选择
        console.log(e)
        if(e==1){
          this.ruleForm.coolingOffDay = ''
          this.$refs['coolingOffDayRef'].clearValidate();
        }
      },
      getInfo() { //获取信息详情
        this.loading = true
        getAreaDetail(this.id).then((res) => {
            let info = res.result
            this.ruleForm.name = info.name
            this.ruleForm.sort = info.sort
            this.ruleForm.coolingOffDay = info.coolingOffDay
            this.ruleForm.coolingOffType = info.coolingOffType
            console.log()
            if (info.areaList.length > 0) {
              info.areaList.forEach(item => {
                var array = []
                array[0] = item.province
                array[1] = item.city
                array[2] = item.area
                this.ruleForm.areaList.push(array)
              })
              console.log('地区', this.ruleForm.areaList)
            }
            setTimeout(() => {
              this.loading = false;
            }, 800)
          })
          .finally(() => {
            setTimeout(() => {
              this.loading = false;
            }, 800)
          });
      },
      submitForm(formName) {
        //创建确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.ruleForm.areaList.length > 0) {
              var areaList = []
              this.ruleForm.areaList.forEach(item => {
                var obj = {}
                obj.province = item[0]
                obj.city = item[1]
                obj.area = item[2]
                areaList.push(obj)
              })
            }
            var params = {
              name: this.ruleForm.name,
              sort: this.ruleForm.sort,
              areaList: areaList,
              coolingOffDay: this.ruleForm.coolingOffDay,
              coolingOffType: this.ruleForm.coolingOffType
            };
            this.submitLoading = true
            addArea(params).then((res) => {
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.submitLoading = false
                }, 1000);
              })
              .finally(() => {
                setTimeout(() => {
                  this.submitLoading = false;
                }, 800)
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      editForm(formName) {
        //编辑确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.ruleForm.areaList.length > 0) {
              var areaList = []
              this.ruleForm.areaList.forEach(item => {
                var obj = {}
                obj.province = item[0]
                obj.city = item[1]
                obj.area = item[2]
                areaList.push(obj)
              })
            }
            var params = {
              name: this.ruleForm.name,
              sort: this.ruleForm.sort,
              areaList: areaList,
              id: this.id,
              coolingOffDay: this.ruleForm.coolingOffDay,
              coolingOffType: this.ruleForm.coolingOffType
            };
            this.submitLoading = true
            editArea(params).then((res) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.submitLoading = false
                }, 1000);
              })
              .finally(() => {
                setTimeout(() => {
                  this.submitLoading = false;
                }, 800)
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
  };

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

</style>
